/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.lnu.ums.ui.converters;

import edu.lnu.ums.entities.Human;
import edu.lnu.ums.service.IDictionaryService;
import edu.lnu.ums.ui.TreeBean;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 *
 * @author Renuald
 */
public class HumanConverter implements Converter {
    public static final String SPACE = " ";

    private IDictionaryService dictionaryService;

    private TreeBean treeBean;

    public HumanConverter() {
        try {
            dictionaryService = (IDictionaryService) InitialContext.doLookup("UMS/DictionaryService/local");
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Object getAsObject(FacesContext fc, UIComponent uic, String string) {
        if ("".equals(string)) {
            return null;
        }

        long id = Long.parseLong(string.split(SPACE)[1]);
        return dictionaryService.getHumanById(treeBean.getSelectedObject(), id);
    }

    @Override
    public String getAsString(FacesContext fc, UIComponent uic, Object o) {
        if (o == null) {
            return "";
        }

        Human hum = (Human)o;
        return "id: " + hum.getId() + SPACE + hum.getName() + SPACE +
                hum.getSecondName() + SPACE + hum.getSurname();
    }

    public TreeBean getTreeBean() {
        return treeBean;
    }

    public void setTreeBean(TreeBean treeBean) {
        this.treeBean = treeBean;
    }

}
